const co = require('co')
const fs = require('fs')
const os = require('os')
const path = require('path')
const CryptoJS = require('crypto-js')
const AES = require('crypto-js/aes')
const iconv = require('iconv-lite')
const exec = require('child_process').exec
const readlineSync = require('readline-sync')

const Browser = require('./browser')

module.exports.login = function(email, password) {
    console.log('=> begin login <=')
    return function(cb) {
        co(function*() {
            let t = Date.now().toString()
            // 生成MAC地址
            let n = [
                (0x52).toString(16),
                (0x54).toString(16),
                (0x00).toString(16),
                Math.floor((Math.random() * 0xff)).toString(16),
                Math.floor((Math.random() * 0xff)).toString(16),
                Math.floor((Math.random() * 0xff)).toString(16)
            ].join(':')
            // 生成设备ID
            let d = CryptoJS.MD5(`${t}_${n}`).toString()
            // 输入：邮箱 密码
            email = email || readlineSync.question('=>    email: ')
            password = password || readlineSync.question('=> password: ') || '1qaz@WSX'
            // 打开图片验证码
            let svg = yield Browser.GET(`https://api.enfi.vip/api/captcha?t==${t}`)
            openSvg(t, svg)
            let cookie = svg.headers['set-cookie'].map(function(e) {
                return e.substring(0, e.indexOf(' path'))
            }).join(' ')
            console.log(cookie)
            // 输入：图片验证码
            let captcha = readlineSync.question('=> captcha: ')
            let login = yield Browser.POST(`https://api.enfi.vip/api/login?plt=win_x64&deviceId=${d}&appver=2.4.0`, {
                'Content-Type': 'application/json',
                'Cookie': cookie,
            }, {
                email: email,
                password: password,
                captcha: captcha,
            })
            let user = login.json
            user.d = d
            user.cookie = cookie
            console.log(user)
            cb(null, user)
        }).catch(function(err) {
            cb(err)
        })
    }
}

module.exports.register = function() {
    console.log('=> begin register, press ENTER skip <=')
    return function(cb) {
        co(function*() {
            let t = Date.now().toString()
            // 生成MAC地址
            let n = [
                (0x52).toString(16),
                (0x54).toString(16),
                (0x00).toString(16),
                Math.floor((Math.random() * 0xff)).toString(16),
                Math.floor((Math.random() * 0xff)).toString(16),
                Math.floor((Math.random() * 0xff)).toString(16)
            ].join(':')
            // 生成设备ID
            let d = CryptoJS.MD5(`${t}_${n}`).toString()
            // 输入：邮箱 图片验证码
            let email = readlineSync.question('=> new email: ')
            if (email == '' || email.trim() == '') {
                console.log(`it's skip`)
                cb(null, {})
                return;
            }
            // 打开图片验证码
            let svg = yield Browser.GET(`https://api.enfi.vip/api/captcha?t==${t}`)
            openSvg(t, svg)
            let cookie = svg.headers['set-cookie'].map(function(e) {
                return e.substring(0, e.indexOf(' path'))
            }).join(' ')
            // 输入：图片验证码
            let captcha = readlineSync.question('=>   captcha: ')
            let send = yield Browser.POST(`https://api.enfi.vip/api/code?plt=win_x64&deviceId=${d}&appver=2.4.0`, {
                'Content-Type': 'application/json',
                'Cookie': cookie,
            }, {
                email: email,
                captcha: captcha,
            })
            console.log(send.json)
            cookie = send.headers['set-cookie'].map(function(e) {
                return e.substring(0, e.indexOf(' path'))
            }).join(' ')
            console.log(cookie)
            // 输入：密码
            let password = readlineSync.question('=>  password: ') || '1qaz@WSX'
            // 输入：邮箱验证码
            let code = yield receiveMail(email, password)
            if (!(code > 0)) {
                code = readlineSync.question('=> mail code: ')
            }
            let register = yield Browser.POST(`https://api.enfi.vip/api/register?plt=win_x64&deviceId=${d}&appver=2.4.0`, {
                'Content-Type': 'application/json',
                'Cookie': cookie,
            }, {
                email: email,
                password: password,
                code: code,
                registerPlatform: 'pc',
            })
            let user = register.json
            user.cookie = cookie
            user.email = email
            user.password = password
            console.log(user)
            cb(null, user)
        }).catch(function(err) {
            cb(err)
        })
    }
}

function openSvg(t, svg) {
    let f = t + '.svg'
    fs.writeFileSync(f, svg.body.replace('width="80" height="30"', 'width="320" height="120"'))
    if (os.platform().indexOf('win32') !== -1) {
        exec('explorer.exe "' + f + '"', function(err, stdout, stderr) {})
    } else {
        exec('open "' + f + '"', function(err, stdout, stderr) {})
    }
    setTimeout(function() {
        if (fs.existsSync(f)) {
            fs.unlinkSync(f)
        }
    }, 888)
}

function receiveMail(email, password) {
    return function(cb) {
        const host = 'pop3.mxhichina.com' // pop3邮箱服务器
        const cmd = `java -jar ${path.join(__dirname, 'receiveMail.jar')} ${email} ${password} ${host}`
        console.log(cmd)
        exec(cmd, function(err, stdout, stderr) {
            let str = iconv.decode(Buffer.from(stdout, 'binary'), 'cp936').trim()
            console.log('receiveMail:', str)
            cb(null, str)
        })
    }
}